<script setup lang="ts">
import { ref } from 'vue';
import { getYear } from '@/hooks/useDate';
import { exeTitleList } from '@/hooks/useCommon';
import { formatZeroValue, formatPercentageValue, useTableHeight } from '@/hooks/useMethod';
import { getDeptList } from '@/api/budget/budgetDept';
import { DeptVO } from '@/api/budget/budgetDept/types';
import { ExeExecuteVO, ExeQueryDTO } from '@/api/fill/execute/exe-business/Types';
import { getDetailList, getList } from '@/api/fill/execute/exe-business';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
const showSearch = ref(true);
const { yard_type, quarter,data_source } = toRefs<any>(proxy?.useDict('yard_type', 'quarter','data_source'));

const deptList = ref<DeptVO[]>([]);

/*预算部门列表*/
const getBudgetDeptList = () => {
  getDeptList(queryParams.value.type).then((res) => {
    deptList.value = res.data;
  });
};
const queryFormRef = ref<ElFormInstance>();

//查询参数
const queryParams = ref<ExeQueryDTO>({
  year: getYear(),
  codeList: [],
  quarter: '1',
  type: 2, //1-（默认一下）
  yard: '',
  subjectCode: '',
  pageNum: 1,
  pageSize: 10
});

/*用于存储表格数据*/
const tableList = ref([]);

/*全部列表查询*/
const getListAll = () => {
  getList(queryParams.value)
    .then((res) => {
      tableList.value = res.data;
      console.log('数据：', res.data);
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getListAll();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    year: getYear(),
    codeList: [],
    type: 2,
    quarter: '1',
    yard: '',
    subjectCode: '',
    pageNum: 1,
    pageSize: 10
  };
  defaultTitle.value = '一季度';
  handleQuery();
};

const defaultTitle = ref('一季度');

//inner弹窗按钮开关
const innerDialog = reactive<DialogOption>({
  visible: false,
  title: '执行明细列表'
});
const total = ref(0);
const showList = ref<ExeExecuteVO[]>([]);

// 独立的获取明细列表方法
const getDetailListData = () => {
  getDetailList(queryParams.value).then((res) => {
    showList.value = res.data.records;
    total.value = res.data.total;
  });
};
//点击
const openShowList = (yardType: string, subjectCode: string) => {
  innerDialog.visible = true;
  console.log(yardType, subjectCode);
  queryParams.value.yard = yardType;
  queryParams.value.subjectCode = subjectCode;
  queryParams.value.pageNum = 1;
  getDetailListData();
};
// 分页处理
const handlePagination = (pagination: any) => {
  queryParams.value.pageNum = pagination.page;
  queryParams.value.pageSize = pagination.limit;
  getDetailListData();
};
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];

  // 先计算所有列的合计值
  const columnSums = {};
  columns.forEach((column, index) => {
    if (index === 0) return;

    const values = data.map(item => Number(item[column.property]) || 0);
    columnSums[column.property] = values.reduce((sum, val) => sum + val, 0);
  });

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    const key = column.property || '';

    // 如果是 rate 相关的列，显示百分比格式
    if (key.includes('rate')) {
      // 提取 rate 后面的数字，比如 rate_1 -> 1
      const rateNumber = key.split('_')[0];

      // 对应的执行数和预算数列名
      const executeKey = `${rateNumber}_execute`;
      const budgetKey = `${rateNumber}_budget`;

      const executeSum = columnSums[executeKey] || 0;
      const budgetSum = columnSums[budgetKey] || 0;

      // 计算百分比
      let percentage = 0;
      if (budgetSum !== 0) {
        percentage = (executeSum / budgetSum) * 100;
      }

      // 向上取整并保留四位小数
      const roundedPercentage = Math.ceil(percentage * 10000) / 10000;
      sums[index] = formatPercentageValue(roundedPercentage / 100);
    } else {
      // 其他列直接使用预先计算的合计值，并向上取整保留四位小数
      const sumValue = columnSums[key] || 0;
      const roundedValue = Math.ceil(sumValue * 10000) / 10000;
      sums[index] = roundedValue;
    }
  });

  return sums;
};
const downloadName = ref(`管理执行表.xlsx`);
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/execute/exe/export',
    {
      ...queryParams.value
    },
    downloadName.value
  );
};
// 使用示例
const tableStyle = useTableHeight(showSearch);
/*挂载生命周期钩子*/
onMounted(() => {
  getBudgetDeptList();
  getListAll();
});
</script>

<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :inline="true">
            <el-form-item label="年份" prop="year">
              <el-date-picker type="year" format="YYYY" value-format="YYYY" v-model="queryParams.year" />
            </el-form-item>
            <el-form-item label="季度" prop="quarter">
              <el-select
                v-model="queryParams.quarter"
                placeholder="请选择季度"
                @change="
                  (value) => {
                    // 根据选中的 value 查找对应的 label
                    const selectedOption = quarter.find((item) => item.value === value);

                    if (selectedOption) {
                      defaultTitle = selectedOption.label; // 设置 label 到 defaultTitle
                      console.log('当前标题:', defaultTitle);
                    } else {
                      defaultTitle = '';
                    }
                  }
                "
              >
                <el-option v-for="dict in quarter" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算部门" prop="codeList" label-width="100px">
              <el-select v-model="queryParams.codeList" placeholder="全部" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptCode" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
          </div>
          <div>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getListAll" />
          </div>
        </div>
      </template>
      <div class="table-class">
        <el-table ref="tableRef" :data="tableList" :style="tableStyle" :show-summary="true" :summary-method="getSummaries"  append class="custom-table enhanced-table">
          <el-table-column prop="subjectCode" label="预算科目编码" v-if="false" align="center" />
          <el-table-column prop="subjectName" label="预算科目" min-width="200" align="center" fixed="left" show-overflow-tooltip></el-table-column>
          <el-table-column v-for="item in exeTitleList" :key="item.key" :label="defaultTitle + item.label" align="center">
            <el-table-column
              v-for="dict in yard_type"
              :key="dict.value"
              :label="dict.label"
              :prop="dict.value + '_' + item.key"
              align="center"
              show-overflow-tooltip
              width="150"
            >
              <template #default="scope">
                <!-- 判断是否需要弹出框 -->
                <template v-if="item.key.includes('execute')">
                  <div class="font-class-green" style="cursor: pointer;" @click="openShowList(dict.value, scope.row.subjectCode)" >
                    {{ formatZeroValue(scope.row[dict.value + '_' + item.key]) }}
                  </div>
                </template>
                <template v-else-if="item.key.includes('rate')">
                  {{ formatPercentageValue(scope.row[dict.value + '_' + item.key]) }}
                </template>
                <template v-else>
                  {{ formatZeroValue(scope.row[dict.value + '_' + item.key]) }}
                </template>
              </template>
            </el-table-column>

            <!-- 合计列 -->
            <el-table-column :prop="'total' + '_' + item.key" label="合计" min-width="180" align="center">
              <template #default="scope">
                <!-- 根据不同的 key 类型使用不同的格式化方法 -->
                <template v-if="item.key.includes('execute')">
                  {{ formatZeroValue(scope.row['total' + '_' + item.key]) }}
                </template>
                <template v-else-if="item.key.includes('rate')">
                  {{ formatPercentageValue(scope.row['total' + '_' + item.key]) }}
                </template>
                <template v-else>
                  {{ formatZeroValue(scope.row['total' + '_' + item.key]) }}
                </template>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-drawer v-model="innerDialog.visible" direction="rtl" :title="innerDialog.title" append-to-body size="1300">
      <el-card shadow="never">
        <!-- 弹出框内容 -->
        <el-table :data="showList" border>
          <el-table-column label="类型" align="center" prop="type" width="100" show-overflow-tooltip />
          <el-table-column label="部门编号" align="center" prop="deptCode" width="100" show-overflow-tooltip />
          <el-table-column label="部门名称" align="center" prop="deptName" width="120" show-overflow-tooltip />
          <el-table-column label="预算科目编码" align="center" prop="subjectCode" width="130" show-overflow-tooltip />
          <el-table-column label="预算科目" align="center" prop="subjectName" width="150" show-overflow-tooltip />
          <el-table-column label="编码" align="center" prop="code" width="150" show-overflow-tooltip />
          <el-table-column label="名称" align="center" prop="name" width="190" show-overflow-tooltip />
          <el-table-column label="金额(元)" align="center" prop="amount" width="130" />
          <el-table-column label="日期" align="center" prop="date" width="150" >
            <template #default="scope">
              <span>{{ parseTime(scope.row.date,'{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center" prop="source" width="100" >
            <template #default="scope">
              <dict-tag :options="data_source" :value="scope.row.source" />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="description" width="280" show-overflow-tooltip />
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </el-card>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss"></style>
